package com.fuint.common.service.impl;

import com.fuint.common.dto.*;
import com.fuint.common.service.ExamReceiveService;
import com.fuint.repository.mapper.MtDeviceItemMapper;
import com.fuint.repository.mapper.MtDeviceRecordMapper;
import com.fuint.repository.mapper.MtExamMemberMapper;
import com.fuint.repository.mapper.MtExamRecordMapper;
import com.fuint.repository.model.MtDeviceItem;
import com.fuint.repository.model.MtDeviceRecord;
import com.fuint.repository.model.MtExamMember;
import com.fuint.repository.model.MtExamRecord;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@AllArgsConstructor
public class ExamReceiveServiceImpl implements ExamReceiveService {

    @Autowired
    private MtExamMemberMapper memberMapper;
    @Autowired
    private MtExamRecordMapper recordMapper;
    @Autowired
    private MtDeviceRecordMapper deviceRecordMapper;
    @Autowired
    private MtDeviceItemMapper deviceItemMapper;

    @Override
    @Transactional
    public void saveExamData(ExamDataDTO2 data) {
        // 保存成员信息
        MemberDTO member = data.getMember();
        MtExamMember mtExamMember = new MtExamMember();
        BeanUtils.copyProperties(member, mtExamMember);
        mtExamMember.setExamNo(data.getExamNo());
        memberMapper.insert(mtExamMember); // 自定义 insertOrUpdate：根据 ID_CODE 唯一索引插入或更新

        // 保存体检主记录
        MtExamRecord record = new MtExamRecord();
        record.setExamNo(data.getExamNo());
        record.setDeviceId(data.getDeviceId());
        record.setExamDate(data.getExamDate());
        record.setExamReportPdfFile(data.getExamReportPdfFile());
        record.setMemberIdCode(member.getIdCode()); // 绑定成员身份证号
        recordMapper.insert(record); // 自定义 insertOrUpdate：根据 EXAM_NO 唯一索引插入或更新

        // 保存设备记录及其明细
        for (RecordDTO recDto : data.getRecord()) {
            MtDeviceRecord deviceRecord = new MtDeviceRecord();
            BeanUtils.copyProperties(recDto, deviceRecord);
            deviceRecord.setExamNo(record.getExamNo()); // 绑定体检编号
            deviceRecordMapper.insert(deviceRecord); // 自定义 insertOrUpdate：根据 RECORD_NO 插入或更新
            // 保存项目明细
            for (ItemDTO item : recDto.getItems()) {
                MtDeviceItem mtDeviceItem = new MtDeviceItem();
                BeanUtils.copyProperties(item, mtDeviceItem);
                //处理区间范围
                if (item.getNormalRange()!=null && item.getNormalRange().size()>0){
                    mtDeviceItem.setNormalRange(item.getNormalRange().get(0)+"-"+item.getNormalRange().get(1));
                }
                mtDeviceItem.setRecordNo(deviceRecord.getRecordNo()); // 绑定设备记录编号
                deviceItemMapper.insert(mtDeviceItem); // 可加重复校验策略（如已有不插入）
            }
        }
    }

}
